import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/report/singleAssignmentData.dart';
import 'package:ichinesereader/pages/teacher/homeworkProgressPerStudent.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class SignleHomeworkDataGrid extends StatelessWidget {
  SignleHomeworkDataGrid(this.assignmentItems, this.assignmentId);

  String assignmentId;
  List<SingleAssignmentData> assignmentItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build SignleAssignmentDataGrid');

    return this.assignmentItems.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid(assignmentId))])
        : Center(child: Text('Data not available ...'));
  }

  SfDataGrid _buildDataGrid(String assignmentId) {
    return SfDataGrid(
      source: AssignmentDataGridSource(
          items: assignmentItems, assignmentId: assignmentId),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      allowSorting: true,
      allowTriStateSorting: true,
      allowFiltering: true,
      allowSwiping: false,
      controller: _dataGridController,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {},
            child: Container(
                color: Colors.redAccent,
                child: Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          width: 180,
          allowFiltering: false,
          columnName: 'FirstName',
          label: buildDataGridColumnLabel('FirstName'),
        ),
        GridColumn(
          width: 180,
          allowFiltering: false,
          columnName: 'LastName',
          label: buildDataGridColumnLabel('LastName'),
        ),
        GridColumn(
          width: 180,
          columnName: 'UserName',
          label: buildDataGridColumnLabel('UserName'),
        ),
        GridColumn(
          columnName: 'Complete',
          width: isWebOrDesktop ? 150 : 140,
          label: buildDataGridColumnLabel('Progress'),
        ),
        GridColumn(
          columnName: 'OverallComplete',
          width: isWebOrDesktop ? 240 : 240,
          label: buildDataGridColumnLabel('Completed/Required/Total Readings'),
        ),
        GridColumn(
          columnName: 'RequiredBooks',
          width: isWebOrDesktop ? 140 : 140,
          visible: false,
          label: buildDataGridColumnLabel('Required Books'),
        ),
        GridColumn(
          columnName: 'TotalBooks',
          allowFiltering: false,
          width: isWebOrDesktop ? 140 : 140,
          visible: false,
          label: buildDataGridColumnLabel('Total Books'),
        ),
        GridColumn(
          columnName: 'Recording',
          width: isWebOrDesktop ? 150.0 : 140.0,
          label: buildDataGridColumnLabel('Recording'),
        ),
        GridColumn(
          columnName: 'Writing',
          width: isWebOrDesktop ? 150.0 : 140.0,
          label: buildDataGridColumnLabel('Writing'),
        ),
        GridColumn(
          columnName: 'Id',
          allowFiltering: false,
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('Id'),
        ),
      ],
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource(
      {required List<SingleAssignmentData> items,
      required String assignmentId}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName',
                  value: dataGridRow.student?.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.student?.lastName),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.student?.userName),
              DataGridCell<bool>(
                  columnName: 'Complete', value: dataGridRow.complete),
              DataGridCell<int>(
                  columnName: 'OverallComplete',
                  value: dataGridRow.overallComplete),
              DataGridCell<int>(
                  columnName: 'RequiredBooks',
                  value: dataGridRow.requiredBooks),
              DataGridCell<int>(
                  columnName: 'TotalBooks', value: dataGridRow.totalBooks),
              DataGridCell<bool>(
                  columnName: 'Recording', value: dataGridRow.recording),
              DataGridCell<bool>(
                  columnName: 'Writing', value: dataGridRow.writing),
              DataGridCell<String>(columnName: 'Id', value: assignmentId),
            ]))
        .toList();
  }

  final box = Hive.box('appconfig');

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    var isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == "UserName") {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: GestureDetector(
                onTap: () {
                  if (isTeacher) {
                    var assignmentId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    Get.to(() => HomeworkProgressPerStudent(
                        assignmentId: assignmentId,
                        userName: dataGridCell.value));
                  }
                },
                child: Text(
                  dataGridCell.value.toString(),
                  style: Get.theme.textTheme.titleLarge,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            );
          } else if (dataGridCell.columnName == 'Complete') {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value ? "Completed" : "InComplete",
                overflow: TextOverflow.ellipsis,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == "OverallComplete") {
            var noOfBookToBeRead = row
                .getCells()
                .where((element) => element.columnName == 'RequiredBooks')
                .first
                .value;
            var numBooks = row
                .getCells()
                .where((element) => element.columnName == 'TotalBooks')
                .first
                .value;
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                "${dataGridCell.value}/$noOfBookToBeRead/$numBooks",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.ellipsis,
              ),
            );
          } else if (dataGridCell.columnName == "Writing" ||
              dataGridCell.columnName == "Recording") {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value ? "Yes" : "No",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.ellipsis,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
